package org.example.mq.common;

import java.io.*;

//负责文件的序列化和反序列化
public class BinaryTool {
    //把一个对象序列化为一个字节数组
    public static byte[] toBytes(Object object) throws IOException {
        //相当于一个变长数组
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){
            try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)){//把byteArrayOutputStream和
                //objectOutputStream关联，相当于写入到了byteArrayOutputStream中
                objectOutputStream.writeObject(object);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }
    public static Object toObject(byte[] data) throws ClassNotFoundException,IOException {
        Object object = null;
        //用的类和序列化的类对应
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data)){
            try(ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)){
               object = objectInputStream.readObject();
            }
        }
        return object;
    }
}
